package com.hly.musicbackground.Utils;

import com.hly.musicbackground.domain.User;
import com.hly.musicbackground.exception.TokenAuthExpiredException;
import com.hly.musicbackground.result.Code;
import com.hly.musicbackground.result.Token;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class RequestContextUtils {

    public static HttpServletRequest getHttpServletRequest(){
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request;
    }

    public static HttpServletResponse getHttpServletResponse(){
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        return response;
    }

    public static String getIPAddress(){
        return IpUtil.getIpAddr(getHttpServletRequest());
    }

    public static User getUser(){
        Token token = (Token) (getHttpServletRequest().getAttribute("token"));
        if (token == null){
            throw new TokenAuthExpiredException(Code.TOKEN_ERR, "未登录，请先登陆");
        }
        User user = new User();
        user.setUserId(Integer.valueOf(token.getId()));
        user.setRoot(Integer.valueOf(token.getRoot()));
        user.setLoginTime(new Date(Long.valueOf(token.getTime())));
        return user;
    }

    public static Token getToken(){
        Token token = (Token) (getHttpServletRequest().getAttribute("token"));
        return token;
    }
}
